package org.museum.identity.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.museum.identity.domain.entity.IdentityName;
import org.museum.identity.mapper.IdentityNameMapper;
import org.museum.identity.service.IdentityNameService;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Slf4j
public class IdentityNameServiceImpl extends ServiceImpl<IdentityNameMapper, IdentityName> implements IdentityNameService {
    @Override
    @Transactional
    public void addIdentityByName(IdentityName entity) {
        // 根据 identity 查询现有记录
        IdentityName existing = this.lambdaQuery()
                .eq(IdentityName::getIdentity, entity.getIdentity())
                .oneOpt()
                .orElse(null);

        if (existing != null) {
            // 名称不同时才更新
            if (!StringUtils.equals(existing.getName(), entity.getName())) {
                // 使用乐观锁更新
                UpdateWrapper<IdentityName> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("id", existing.getId())
                        .set("name", entity.getName());
                this.update(updateWrapper);
            }
            // 名称相同时返回true，但记录日志
            log.info("身份证 {} 已存在且名称相同，无需更新", entity.getIdentity());
            return;
        }

        // 插入新记录
        try {
            this.save(entity);
        } catch (DuplicateKeyException e) {
            // 处理并发插入的情况
            log.warn("身份证 {} 插入冲突，可能已被其他请求创建", entity.getIdentity());
        }
    }

    @Override
    public String selectNameByIdCard(String identity) {
        return baseMapper.selectNameByIdCard(identity);
    }
}
